# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
每日通话时长
"""
from util import (
    logging,
    write_excel,
    query_es,
    time,
    date_slice,
    ms2min,
    excel_save_dir,
)


class ExportDailyBills:
    def __init__(self, ui_data):
        self.data_date = ui_data["data_date"]
        self.business = ui_data.get("business")
        self.data_type = ui_data.get("data_type")
        self.call_type = ui_data.get("call_type")
        self.start_time = ui_data.get("start_time")
        self.end_time = ui_data.get("end_time")
        company_id = ui_data.get("company_id")
        self.db_name = f"yicall_{company_id}"
        self.table_index = ui_data.get("business_id")
        if self.call_type == "呼出":
            self.es_index = f"{self.db_name}_{self.table_index}_callout_session_ach_{self.data_date}"
        else:
            self.es_index = f"{self.db_name}_{self.table_index}_callout_session_in_ach_{self.data_date}"

    def query_es_data(self, day_start_time, day_end_time):
        """"""
        body = {
            "query": {
                "bool": {
                    "must": [
                        {"term": {"calloutConnectStatus": 100}},
                        {
                            "range": {
                                "calloutFinishTime": {
                                    "gte": day_start_time,
                                    "lte": day_end_time,
                                }
                            }
                        },
                    ]
                }
            }
        }
        fields = ["calloutDialTime", "dialogDuration"]
        day_es_data = query_es(self.es_index, body, fields)
        return day_es_data

    def export(self):
        # 以“天”为单位查询es数据，避免scroll超时
        bills = dict()
        date_slice_result = date_slice(self.start_time, self.end_time)
        handle_data_start_time = time.time()
        for everyday in date_slice_result:
            day_start_time = everyday[0]
            day_end_time = everyday[1]
            day_es_data = self.query_es_data(day_start_time, day_end_time)
            for data in day_es_data:
                dial_date = data.get("calloutDialTime")[:10]
                dialog_duration = data.get("dialogDuration")
                dialog_duration_min = ms2min(int(dialog_duration))
                find_dial_data = bills.get(dial_date, -1)
                if find_dial_data != -1:
                    bills[dial_date] += dialog_duration_min
                else:
                    bills[dial_date] = dialog_duration_min
        handle_data_end_time = time.time()
        handle_data_take_time = handle_data_end_time - handle_data_start_time
        logging.info(
            f"处理从ElasticSearch中查询出来的数据共计耗时{handle_data_take_time:.2f}秒。"
        )
        if bills:
            # 分批次查询和写入数据
            excel_names = list()
            excel_data = list()
            date_order = sorted(bills.keys())
            for date in date_order:
                duration_min = bills.get(date)
                excel_data.append([date, duration_min])
            excel_data.append(["总计", f"=SUM(B2:B{len(excel_data) + 1})"])
            excel_title = ["日期", "通话时长(分钟)"]
            file_name = (
                f"{self.business}_({self.call_type}){self.data_type}_{self.data_date}"
            )
            write_excel_start_time = time.time()
            excel_name = write_excel(
                [[self.data_type, excel_title, excel_data]], excel_save_dir, file_name
            )
            write_excel_end_time = time.time()
            write_excel_take_time = write_excel_end_time - write_excel_start_time
            logging.info(
                f"将{self.business}的{self.data_type}写入excel共计耗时{write_excel_take_time:.2f}秒。"
            )
            excel_names.append(excel_name)
            return {"code": 0, "excel_names": excel_names, "msg": None}
        else:
            msg = (
                f"<font color=green>无法导出“{self.business}”的【{self.data_type}】，"
                f"原因：\n在{self.start_time}至{self.end_time}没有{self.call_type}数据！</font>"
            )
            logging.info(msg)
            return {"code": 1, "excel_names": [], "msg": msg}


if __name__ == "__main__":
    ...
